package com.zidian.study.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/9/13 0013.
 * 登录页面
 */
public class LoginActivity extends AppCompatActivity {

    @Bind(R.id.student_account)
    EditText studentAccount;
    @Bind(R.id.student_password)
    EditText studentPassword;
    @Bind(R.id.login_btn)
    Button loginBtn;
    private Intent intent;
    private final static String TAG = "JPush";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        intent = new Intent(this, MainActivity.class);
        intent.putExtra("isShowNoticeMsg", true);
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
        if (sharedPreferences.getBoolean("isLogin", false)) {
            login(sharedPreferences.getString("account", ""), sharedPreferences.getString("password", ""));
        } else {
            setContentView(R.layout.activity_login2);
            setTitle("登录");
            ButterKnife.bind(this);
            studentAccount.setText(sharedPreferences.getString("account", ""));
            initView();
        }
    }

    private void initView() {

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = studentAccount.getText().toString().trim();
                String password = studentPassword.getText().toString().trim();
                if (TextUtils.isEmpty(account)) {
                    Snackbar.make(loginBtn, "请输入用户名", Snackbar.LENGTH_SHORT).show();
                }
                if (TextUtils.isEmpty(password)) {
                    Snackbar.make(loginBtn, "请输入密码", Snackbar.LENGTH_SHORT).show();
                }
                loginUpdata(account, password);
            }
        });

    }


    private void loginUpdata(String userName, String password) {
        String loginUrl = Constant.URL_GOAL + "shiro/loginStudent";
        HashMap<String, String> map = new HashMap<>();
        map.put("username", userName);
        map.put("password", password);

        ProgressBarBlackUtil.loadShow(this);

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                Snackbar.make(loginBtn, "登录失败!", Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(studentPassword, jsonObject.getString("message"), Snackbar.LENGTH_SHORT).show();
                        return;
                    } else {
                        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("account", studentAccount.getText().toString().trim());
                        editor.putString("password", studentPassword.getText().toString().trim());
                        editor.putString("studentId", jsonObject.getString("studentId"));
                        editor.putString("studentName", jsonObject.getString("studentName"));
                        editor.putString("token", jsonObject.getString("token"));
                        editor.putBoolean("isLogin", true);
                        editor.commit();
                        //设置标签
                        Set<String> set = new HashSet<String>();
                        set.add(jsonObject.getString("studentClass"));
                        setJPushTag(set);
                        startActivity(intent);
                        finish();
                        return;
                    }

                } catch (JSONException e) {

                }

            }
        });
    }

    private void login(String userName, String password) {
        String loginUrl = Constant.URL_GOAL + "shiro/loginStudent";
        HashMap<String, String> map = new HashMap<>();
        map.put("username", userName);
        map.put("password", password);


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                editor.putBoolean("isLogin", false);
                editor.commit();
                finish();
                startActivity(new Intent(LoginActivity.this, LoginActivity.class));
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.clear();
                        editor.commit();
                        Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                        return;
                    } else {
                        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USER_INFO_KEY, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("token", jsonObject.getString("token"));
                        editor.putBoolean("isLogin", true);
                        editor.commit();
                        //设置标签
                        Set<String> set = new HashSet<String>();
                        set.add(jsonObject.getString("studentClass"));
                        setJPushTag(set);
                        startActivity(intent);
                        finish();
                        return;
                    }

                } catch (JSONException e) {

                }

            }
        });
    }

    /**
     * 设置TAG
     *
     * @param tag
     */
    private void setJPushTag(Set<String> tag) {
        JPushInterface.setAliasAndTags(getApplicationContext(), null, tag, new TagAliasCallback() {
            @Override
            public void gotResult(int code, String s, Set<String> set) {
                String logs;
                switch (code) {
                    case 0:
                        logs = "Set tag and alias success";
                        Log.i(TAG, logs);
                        break;

                    case 6002:
                        logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                        Log.i(TAG, logs);
                        break;

                    default:
                        logs = "Failed with errorCode = " + code;
                        Log.e(TAG, logs);
                }
            }
        });
    }

}
